/*
 * protocol.c
 *
 *  Created on: Jun 7, 2012
 *      Author: esl32
 */

#include "fcntl.h"
#include "protocol.h"

int parse_next(SerialConn* conn, unsigned char c)
{
   if (conn->state == START)
   {
      if (c == DLE)
         conn->state = FRAMEDLE;
   }
   else if (conn->state == FRAMEDLE)
   {
      if (c == DLE || c == ETX)
         conn->state = START;
      else
      {
         conn->state = DATA;
         conn->length = 1;
         conn->checksum = c;
         conn->packetBuffer[0] = c;
      }
   }
   else if (conn->state == DATA)
   {
      if (c == DLE)
      {
         conn->state = DATADLE;
      }
      else
      {
         conn->checksum ^= c;
         conn->packetBuffer[conn->length] = c;
         conn->length++;
      }
   }
   else if (conn->state == DATADLE)
   {
      if (c == DLE)
      {
         conn->checksum ^= c;
         conn->packetBuffer[conn->length] = c;
         conn->length++;
         conn->state = DATA;
      }
      else if (c == ETX)
      {
         conn->state = START;
         if (conn->checksum == 0)
         {
            return READY;
         }
         else
         {
            return CHECKSUM_INCORRECT;
         }
      }
      else
      {
         conn->state = START;
         return MALFORMED;
      }
   }
   return PARSING;
}

void write_packet(int fd, unsigned char* msg, int length)
{
   int i;
   char txBuffer[40];
   char check = 0;
   int cur_length = 1;
   txBuffer[0] = 0x10;
   for (i = 0; i < length; i++)
   {
      txBuffer[cur_length] = msg[i];
      cur_length++;
      if (msg[i] == 0x10)
      {
         txBuffer[cur_length] = msg[i];
         cur_length++;
      }
      check ^= msg[i];
   }
   txBuffer[cur_length] = check;
   cur_length++;
   txBuffer[cur_length] = 0x10;
   cur_length++;
   txBuffer[cur_length] = 0x03;
   cur_length++;

   write(fd, txBuffer, cur_length);
}

/*int open_conn(char* location, SerialConn* conn)
{
   int fd;
   struct termios tty_attributes;
   struct serial_rs485 rs485conf;

   if ((fd = open(location, O_RDWR | O_NOCTTY | O_NONBLOCK)) < 0)
   {
      fprintf(stderr, "Open error on %s\n", strerror(errno));
      return 1;
   }
   else
   {
      tcgetattr(fd, &tty_attributes);
      cfmakeraw(&tty_attributes);
      tcsetattr(fd, TCSANOW, &tty_attributes);
      conn->fd = fd;
      conn->length = 0;
   }

   return 0;
}*/

